package service

import (
	"fmt"
	context3 "ksd-social-api/modules/msg/model/context"
	cmodel "ksd-social-api/modules/note/model"
)

/**
 * 用户购买小册
 * @author feige
 * @date 2023-11-23
 * @version 1.0
 * @desc
 */
type UserNoteService struct {
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  保存用户购买专栏信息
 */
func (service *UserNoteService) SaveUserNote(
	OutTradeNo string, TransactionId string, orderJson string, payMethod int, payMethodName string, price string,
	userId uint64, opid uint64, systemId uint64, systemName string) bool {
	// 1： 判断用户是否购买此课程，如果购买过了就就不要去保存订单
	isBuyFlag := userBuyNoteMapper.CountUserBuyNoteNo(userId, opid, systemId)
	if isBuyFlag == 0 {
		userBuyNote := cmodel.UserBuyNote{}
		// 根据课程id查询课程信息
		note, _ := noteMapper.GetById(opid, systemId)
		userVo := userMapper.GetUserByID(userId, systemId)

		userBuyNote.SystemId = systemId
		userBuyNote.SystemName = systemName
		// 处理返回结果
		userBuyNote.Opid = opid
		userBuyNote.Title = note.Title
		userBuyNote.Cover = note.Img

		userBuyNote.UserId = userId
		userBuyNote.Username = userVo.Username
		userBuyNote.Avatar = userVo.Avatar
		userBuyNote.Uuid = userVo.Uuid
		userBuyNote.Phone = userVo.Telephone
		userBuyNote.Address = userVo.Address
		userBuyNote.Nickname = userVo.Nickname

		userBuyNote.ChannelId = note.ChannelId
		userBuyNote.ChannelName = note.ChannelName

		userBuyNote.Code = ""
		userBuyNote.SpecialId = note.SpecialId
		userBuyNote.PayMethod = payMethod
		userBuyNote.PayMethodName = payMethodName
		userBuyNote.Tradeno = OutTradeNo
		userBuyNote.Orderno = TransactionId
		userBuyNote.OrderJson = orderJson
		userBuyNote.Price = price
		userBuyNoteMapper.SaveUserBuyNote(userBuyNote)

		// 保存消息
		messageMeContext := context3.MessageMeContext{}
		messageMeContext.UserId = userId
		messageMeContext.Title = note.Title
		messageMeContext.Uuid = userVo.Uuid
		messageMeContext.SystemId = systemId
		messageMeContext.SystemName = "系统512"
		messageMeContext.Username = userVo.Nickname
		if note.ChapterFlag == 1 {
			messageMeContext.Url = fmt.Sprintf("https://www.study512.com/note/page/%d", note.Id)
		} else {
			messageMeContext.Url = fmt.Sprintf("https://www.study512.com/note/detail/%d", note.Id)
		}
		messageMeService.SaveMessageMeBuyNote(&messageMeContext)
		return true
	}
	return false
}

/**
 * @author feige
 * @date 2023-10-10
 * @version 1.0
 * @desc  判断用户是否购买此小册
 */
func (service *UserNoteService) CountUserBuyNote(userId uint64, noteId uint64, systemId uint64) bool {
	// 1： 判断用户是否购买此小册，如果购买过了就就不要去保存订单
	isBuyFlag := userBuyNoteMapper.CountUserBuyNoteNo(userId, noteId, systemId)
	return isBuyFlag == 0
}

/*
*
统计用户已经支付小册的金额
*/
func (service *UserNoteService) SumUserByNote(specailId uint64, userId uint64, systemId uint64) float64 {
	return userBuyNoteMapper.SumUserByNote(specailId, userId, systemId)
}
